//
//  lyricsSV.swift
//  QQMusic
//
//  Created by xmg on 16/9/8.
//  Copyright © 2016年 wlis. All rights reserved.
//

import UIKit


private let lyricsCellID = "lyricsCellID"

/** 设置代理 */
protocol lyricsSVDelegate{

    /** 显示歌词 */
    func lyricsSVText(lrcView :lyricsSV, lrcText : String, progress : CGFloat)
    /** 画图片上的歌词 */
    func lyricsSVImage(lrcView : lyricsSV, drawImage : UIImage)
}

class lyricsSV: UIScrollView {
    /** 创建UITableView */
    private lazy var tableView : UITableView = UITableView()
    
    var lyricsDelegate : lyricsSVDelegate?
    var lyricsItems : [lyricsItem]?
    var currentIndex : Int = -1;
    var iconName : String = ""
    var lrcName : String = "" {
        didSet{
        lyricsItems =  lyricsParseTools.lyricsToolsWithFileName(lrcName)
            tableView.reloadData()
            
            /** 滚动到最上面 */
            let offset = CGPoint(x: 0, y: -self.bounds.height * 0.4 )
            tableView.setContentOffset(offset, animated: true)
        }
    }
    var currentTime : NSTimeInterval = 0{
        didSet{
            /** 歌词是否幼稚 */
            guard let lyricsItem = lyricsItems else{return}
            /** 获取歌词数量 */
            let count = lyricsItem.count
            /** 遍历 */
            for i  in 0..<count {
                /** 获取歌词 */
            let lrcline = lyricsItem[i]
                let nextIndex = i + 1
                /** 判断边界 */
                if nextIndex > count - 1{break}
                let nextlrcline = lyricsItem[nextIndex]
                /** 判断歌词 显示i的位置歌词 */
                if currentTime >= lrcline.lrcTime && currentTime < nextlrcline.lrcTime && currentIndex != i{
                let indexPath = NSIndexPath(forRow: i, inSection: 0)
                    currentIndex = i
                    tableView.reloadData()
                    /** 滚动到歌词位置 */
                    tableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: .Middle, animated: true)
                    drawIconLRC()
                }
                if currentIndex == i {
                let progress = (currentTime - lrcline.lrcTime) / (nextlrcline.lrcTime - lrcline.lrcTime)
                    let indexPath = NSIndexPath(forRow: i, inSection: 0)
                    guard let cell = tableView.cellForRowAtIndexPath(indexPath) as? lyricsCell else{
                    continue}
                    /** 刷新歌词进度 */
                    cell.lyricsLabels.progress = CGFloat(progress)
                    /** 代理 */
                    lyricsDelegate?.lyricsSVText(self, lrcText: lrcline.lrcText, progress: CGFloat(progress))
                }
            }
            
            
        }
        
        
        
        
    }
    override func awakeFromNib() {
        super.awakeFromNib()
        setUpTableView()
    }
    override func layoutSubviews() {
        super.layoutSubviews()
        /** 设置frame */
        tableView.frame = CGRect(x: bounds.width, y: 0, width: bounds.width, height: bounds.height)
        /** 设置内边距 */
        let insetMarin = bounds.width * 0.5
        tableView.contentInset = UIEdgeInsets(top: insetMarin, left: 0, bottom: insetMarin, right: 0)
//      tableView.autoresizingMask = UIViewAutoresizing.None
    }
}

extension lyricsSV{
    /** 设置TableView的属性 */
    private func setUpTableView(){
    addSubview(tableView)
        tableView.registerClass(lyricsCell.self, forCellReuseIdentifier: lyricsCellID)
        tableView.dataSource = self
        tableView.backgroundColor = UIColor.clearColor()
        tableView.separatorStyle = .None
        tableView.rowHeight = 31.5
        
    }
    /** 给图片画歌词 */
    private func drawIconLRC (){
        guard let lyricsItem = lyricsItems else{return}
        /** 获取图片 */
        guard let image = UIImage(named: iconName)else{return}
        /** 开启图片上下文 */
        UIGraphicsBeginImageContextWithOptions(image.size, true, 0.0)
        image.drawInRect(CGRect(origin: CGPointZero, size: image.size))
        // 4.获取歌词
        // 4.1.获取上一句歌词
        var previousLrc = ""
        if currentIndex - 1 >= 0 {
            previousLrc = lyricsItem[currentIndex - 1].lrcText
        }
        
        // 4.2.获取当前句歌词
        let currentLrc = lyricsItem[currentIndex].lrcText
        
        // 4.3.取出下一句歌词
        var nextLrc = ""
        if currentIndex + 1 <= lyricsItem.count - 1 {
            nextLrc = lyricsItem[currentIndex + 1].lrcText
        }
        
        // 5.将歌词画到上下文中
        let lrcW : CGFloat = image.size.width
        let lrcH : CGFloat = 25
        
        let style = NSMutableParagraphStyle()
        style.alignment = .Center
        let attrs = [NSForegroundColorAttributeName : UIColor.whiteColor(),
            NSParagraphStyleAttributeName : style ]
        
        // 5.1.画出下一句歌词
        let nextRect = CGRect(x: 0, y: image.size.height - lrcH, width: lrcW, height: lrcH)
        (nextLrc as NSString).drawInRect(nextRect, withAttributes: attrs)
        
        // 5.2.画出当前句歌词
        let currentRect = CGRect(x: 0, y: image.size.height - 2 * lrcH, width: lrcW, height: lrcH)
        (currentLrc as NSString).drawInRect(currentRect, withAttributes: attrs)
        
        // 5.3.画出上一句歌词
        let previousRect = CGRect(x: 0, y: image.size.height - 3 * lrcH, width: lrcW, height: lrcH)
        (previousLrc as NSString).drawInRect(previousRect, withAttributes: attrs)
        
        // 6.从上下文中获取图片
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        
        // 7.关闭上下文
        UIGraphicsEndImageContext()
        
        lyricsDelegate?.lyricsSVImage(self, drawImage: newImage)
        
    }
}
extension lyricsSV : UITableViewDataSource{

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return lyricsItems?.count ?? 0
    }
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell :lyricsCell = tableView.dequeueReusableCellWithIdentifier(lyricsCellID, forIndexPath: indexPath) as! lyricsCell
        if indexPath.row != currentIndex{
        cell.lyricsLabels.progress = 0.0
        }
        let lrcItem = lyricsItems![indexPath.row]
        cell.lyricsLabels.text = lrcItem.lrcText
        
        return cell
        
    }
}